<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar left-arrow title="搜索中心" @click-left="$router.back()" />
    <!-- 搜索栏 -->
    <van-search
      v-model="key"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 历史记录区域 -->
    <van-cell-group v-if="!key">
      <van-cell title="历史记录" />
      <van-cell v-for="(item,index) in historyList" :key="index" :title="item" @click="toResult(item)"/>
    </van-cell-group>
    <!-- 搜索建议区域 -->
    <van-cell-group v-else>
      <van-cell v-for="(item,index) in colorList" :key="index" icon="search"  >
        <div @click="toResult( suggestList[index]  )" v-html="item"></div>
    </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { suggestAPI } from '@/api/search'
export default {
  name: 'MySearch',
  data () {
    return {
      key: '',
      suggestList: [],
      // 取出之前存的历史记录
      historyList: JSON.parse(localStorage.getItem('history98')) || []
    }
  },
  methods: {
    toResult (item) {
      this.key = item
      this.onSearch()
    },
    onSearch () {
      if (this.key.trim() === '') return this.$toast('请输入搜索内容')

      // 跳转之前把搜索记录存起来
      // 判断当前搜索的内容是否在数组里
      const idx = this.historyList.indexOf(this.key)
      if (idx !== -1) {
        // 在数组里，在数组里先把它删掉
        this.historyList.splice(idx, 1)
      }
      // 把搜索的内容加到数组里
      this.historyList.unshift(this.key)
      localStorage.setItem('history98', JSON.stringify(this.historyList))

      // 跳转到搜索结果
      this.$router.push({
        name: 'result',
        query: {
          key: this.key
        }
      })
    },
    // 输入内容变化触发的事件
    async onInput () {
      if (this.key === '') return
      // 发请求获取建议
      const res = await suggestAPI({
        q: this.key
      })
      // 这个接口没写好
      if (res.data.options[0]) {
        this.suggestList = res.data.options
      } else {
        this.suggestList = []
      }
    }
  },

  computed: {
    colorList () {
      return this.suggestList.map(v => {
        // 找到输入的关键字，把它替换成`<span>`包住
        return v.replace(this.key, `<span style="color:red;">${this.key}</span>`)
      })
    }
  }
}
</script>

<style></style>
